<template>
  <el-tree :data="permissionList"
           :props="defaultProps"
           :default-checked-keys="defaultIds"
          
           show-checkbox
           node-key="id"
           @check="checkTree" />
</template>
<!-- :default-expand-all="true"-->
<script setup>
import {ref, watch} from 'vue'
import {doGet} from "@/config/http"
import {getListPageSize, svc} from "@/config/common"

const props = defineProps({
  checkedIdList: {
    required: false,
    type: Array
  },
})

const emit = defineEmits(['checkedTree'])

let permissionList = ref([])
let defaultIds = ref([])

const defaultProps = {
  children: 'children',
  label: 'permissionName',
}

watch(() => [props.checkedIdList], async vals => {
  defaultIds.value = vals[0]
  let res = await doGet(svc, '/permission/page', {pageSize: getListPageSize(), state: '1', sortField: 'id', sortType: 'asc'})
  permissionList.value = treeCompose(res['records'])
}, {immediate: true})

function checkTree(nodeObj, selectedObj) {
  emit('checkedTree', selectedObj.checkedKeys)
}

// 组装权限树结构
function treeCompose(list, pid) {
  return list
      .filter((item) =>
          !pid ? item.parentId === null : item.parentId === pid
      )
      .map(item => {
        item.children = treeCompose(list, item.id);
        return item;
      });
}
</script>
